package modele;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Game {

	protected Collection<Player> collec_players;
	protected Board board;
	protected Iterator<Player> current_player;

	public Game(Board board, ArrayList<Player> players) {
		collec_players = players;
		this.board = board;
		current_player = collec_players.iterator();
	}

	public static void main(String[] args) {
		Board brd = new Board();
		Cell startCell = brd.lst[0];
		ArrayList<Player> players = new ArrayList<Player>();

		brd.chooseNamesByInput(players, startCell);

		System.out.println("~~~~~~~~~~~~~~~~~~~~~\nPlayers : " + players
				+ " \n~~~~~~~~~~~~~~~~~~~~~");

		Game g = new Game(brd, players);
		g.play();
	}

	/**
	 * Starts the game and creates the loop of turns.
	 */
	public void play() {
		while (!isFinished())
			board.playTurn(nextPlayer(), throwDie() + throwDie());
	}

	/**
	 * Indicates the next player to play.
	 * 
	 * @return the next <code>Player</code>
	 */
	public Player nextPlayer() {
		if (!current_player.hasNext())
			current_player = collec_players.iterator();
		return current_player.next();
	}

	/**
	 * Generate a random int to simulate a die.
	 * 
	 * @return an int between 1 and 6.
	 */
	public int throwDie() {
		return (int) (Math.random() * 6) + 1;
	}

	/**
	 * Indicates if a player reached the End Cell.
	 * 
	 * @return true if a player reached the End Cell, false if not.
	 */
	public boolean isFinished() {
		if (board.getEndCell().isBusy()) {
			System.out.println("Congratulations, "
					+ board.getEndCell().getPlayer() + " won the game !");
			return true;
		}
		for (Player p : collec_players)
			if (p.current_cell.canBeLeftNow())
				return false;
		System.out.println("All the players are blocked : The game is over");
		return true;
	}

	public Collection<Player> getCollectPlayer(){
		return this.collec_players;
	}

}
